//
//  CitySelectViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-23.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "CitySelectViewController.h"
#import "Config.h"
#import "Helper.h"

//  -业务逻辑细节说明-
//
//  @abstract       此VC并没有复杂的逻辑，webview加载完成后，将所有的二级城市数据显示出来，然后确定是否要默认勾选二级城市（用户修改的情况）。
//                  每次保存时都调用一次JS方法获取当前哪些二级城市被选择，获得数据后，再传递给上级页面，通常是省市选择VC。

//  @discussion
//

//  @notes


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface CitySelectViewController ()

@end

@implementation CitySelectViewController
@synthesize delegate = _delegate;
@synthesize currentCities = _currentCities;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithProvince:(NSDictionary *)province
{
    self = [super init];
    if (self) {
        
        _provinceName = province[@"name"];
        _citiesInProvince = province[@"cities"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //保存
    UIButton *saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"select_city" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f)];
    _webView.delegate = self;
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件
- (void)backButtonEvent:(id)sender
{
    
    if ([_currentCities isEqualToString:[_webView stringByEvaluatingJavaScriptFromString:@"select_result();"]]) {
    
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_124") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 1;
        [alertView show];
    }

}

- (void)saveButtonEvent:(id)sender
{
    if ([_delegate respondsToSelector:@selector(citiesDidSelected:inProvince:)]) {
        [_delegate citiesDidSelected:[_webView stringByEvaluatingJavaScriptFromString:@"select_result();"] inProvince:_provinceName];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (_citiesInProvince == nil || _citiesInProvince.count == 0) {
        return;
    }
    
    //拼接javascript语法的数组字符串，传递给HTML
    NSString *str = @"var cities = new Array(";
    
    //解析字符串
    for (int i = 0; i<_citiesInProvince.count; i++) {
        
        if (i != 0) {
            str = [str stringByAppendingString:@","];
        }
        str = [str stringByAppendingFormat:@"'%@'",_citiesInProvince[i][@"name"]];
    }
    
    str = [str stringByAppendingString:@")"];
    
    [_webView stringByEvaluatingJavaScriptFromString:str];
    
    [_webView stringByEvaluatingJavaScriptFromString:@"show();"];
    
    if (_currentCities != nil) {
        
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"select_cities(\"%@\");",_currentCities]];
    }
    
//    NSLog(@"传递的二级城市%@",_currentCities);
}

#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
@end
